import { useState, useEffect, useCallback, useMemo } from 'react';
import type { TableProps, PaginationProps, InputProps } from 'antd';

// 类型定义
interface RequestParams {
  current: number;
  pageSize: number;
  [key: string]: any;
}

interface ResponseData<T = any> {
  list: T[];
  total: number;
  current?: number;
  pageSize?: number;
}

interface FilterConfig {
  dataIndex: string;
  placeholder?: string;
  debounce?: number;
}

interface FieldMapping {
  list?: string;
  total?: string;
  current?: string;
  pageSize?: string;
}

interface UseDataTableOptions<T = any> {
  // 数据源配置
  url?: string;
  data?: T[]; // 静态数据源
  params?: Record<string, any>;

  // 表格配置
  columns: TableProps<T>['columns'];
  rowKey?: string | ((record: T) => string);
  immediate?: boolean;

  // 数据转换
  transformData?: (data: any) => ResponseData<T>;
  fieldMapping?: FieldMapping;

  // 筛选配置
  filter?: FilterConfig;

  // 分页配置
  pagination?: boolean | PaginationProps;

  // 请求配置
  request?: (params: any) => Promise<any>;
}

interface UseDataTableReturn<T = any> {
  // 核心属性
  tableProps: TableProps<T>;
  data: T[];
  loading: boolean;
  total: number;

  // 分页相关
  paginationProps: PaginationProps;
  current: number;
  pageSize: number;

  // 筛选相关
  filterProps: InputProps;
  filterValue: string;

  // 操作方法
  refresh: () => void;
  search: (params: Record<string, any>) => void;
  reset: () => void;
  setData: (data: T[]) => void;
  setLoading: (loading: boolean) => void;
}

// 工具函数：获取嵌套对象属性值
const getNestedValue = (obj: any, path: string): any => {
  if (!path) return undefined;
  return path.split('.').reduce((acc, part) => acc && acc[part], obj);
};

// 主 Hook 实现
export const useDataTable = <T = any>(options: UseDataTableOptions<T>): UseDataTableReturn<T> => {
  const {
    // 数据源
    url,
    data: staticData,
    params: initialParams = {},

    // 表格配置
    columns,
    rowKey = 'id',
    immediate = true,

    // 数据转换
    transformData,
    fieldMapping = {
      list: 'list',
      total: 'total',
      current: 'current',
      pageSize: 'pageSize',
    },

    // 筛选配置
    filter,

    // 分页配置
    pagination: paginationConfig = true,

    // 自定义请求
    request,
  } = options;

  // 状态管理
  const [data, setData] = useState<T[]>([]);
  const [loading, setLoading] = useState(false);
  const [total, setTotal] = useState(0);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
  });
  const [searchParams, setSearchParams] = useState<Record<string, any>>(initialParams);
  const [filterValue, setFilterValue] = useState('');
  const [filteredData, setFilteredData] = useState<T[]>([]);
  const [debounceTimer, setDebounceTimer] = useState<NodeJS.Timeout | null>(null);

  // 判断是否使用静态数据
  const isStaticData = !!staticData;

  // 获取表格数据
  const fetchData = useCallback(async () => {
    if (isStaticData) {
      // 使用静态数据
      setData(staticData);
      setTotal(staticData.length);
      return;
    }

    if (!url && !request) {
      console.warn('useDataTable: 请提供 url 或 request 参数');
      return;
    }

    setLoading(true);
    try {
      const requestParams: RequestParams = {
        current: pagination.current,
        pageSize: pagination.pageSize,
        ...searchParams,
      };

      let result;
      if (request) {
        // 使用自定义请求方法
        result = await request(requestParams);
      } else if (url) {
        // 使用默认 fetch
        const response = await fetch(url, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(requestParams),
        });
        result = await response.json();
      }

      // 数据提取和转换
      let finalData: ResponseData<T>;
      if (transformData) {
        finalData = transformData(result);
      } else {
        const listData = getNestedValue(result, fieldMapping.list!) || [];
        const totalCount = getNestedValue(result, fieldMapping.total!) || 0;
        const currentPage = getNestedValue(result, fieldMapping.current!);
        const pageSizeValue = getNestedValue(result, fieldMapping.pageSize!);

        finalData = {
          list: listData,
          total: totalCount,
          current: currentPage,
          pageSize: pageSizeValue,
        };
      }

      setData(finalData.list || []);
      setTotal(finalData.total || 0);
      
      // 更新分页信息
      if (finalData.current) {
        setPagination(prev => ({
          ...prev,
          current: finalData.current!,
        }));
      }
      if (finalData.pageSize) {
        setPagination(prev => ({
          ...prev,
          pageSize: finalData.pageSize!,
        }));
      }
    } catch (error) {
      console.error('表格数据请求失败:', error);
      setData([]);
      setTotal(0);
    } finally {
      setLoading(false);
    }
  }, [
    url,
    staticData,
    isStaticData,
    pagination.current,
    pagination.pageSize,
    searchParams,
    transformData,
    fieldMapping.list,
    fieldMapping.total,
    fieldMapping.current,
    fieldMapping.pageSize,
    request,
  ]);

  // 筛选数据
  useEffect(() => {
    if (!filterValue || !filter) {
      setFilteredData(data);
      return;
    }

    const filtered = data.filter(item => {
      const fieldValue = getNestedValue(item, filter.dataIndex);
      return String(fieldValue || '').toLowerCase().includes(filterValue.toLowerCase());
    });
    
    setFilteredData(filtered);
  }, [data, filterValue, filter]);

  // 处理筛选变化（防抖）
  const handleFilterChange = useCallback((value: string) => {
    setFilterValue(value);
    
    if (debounceTimer) {
      clearTimeout(debounceTimer);
    }

    const timer = setTimeout(() => {
      if (!isStaticData) {
        setPagination(prev => ({ ...prev, current: 1 }));
      }
    }, filter?.debounce || 300);

    setDebounceTimer(timer);
  }, [debounceTimer, filter?.debounce, isStaticData]);

  // 清除防抖定时器
  useEffect(() => {
    return () => {
      if (debounceTimer) {
        clearTimeout(debounceTimer);
      }
    };
  }, [debounceTimer]);

  // 初始化数据
  useEffect(() => {
    if (immediate && !isStaticData) {
      fetchData();
    } else if (isStaticData) {
      setData(staticData);
      setTotal(staticData.length);
    }
  }, [fetchData, immediate, isStaticData, staticData]);

  // 刷新数据
  const refresh = useCallback(() => {
    if (isStaticData) {
      setData(staticData);
      setTotal(staticData.length);
    } else {
      fetchData();
    }
  }, [fetchData, isStaticData, staticData]);

  // 搜索
  const search = useCallback((params: Record<string, any>) => {
    setSearchParams(prev => ({ ...prev, ...params }));
    if (!isStaticData) {
      setPagination(prev => ({ ...prev, current: 1 }));
    }
  }, [isStaticData]);

  // 重置
  const reset = useCallback(() => {
    setSearchParams(initialParams);
    setFilterValue('');
    if (!isStaticData) {
      setPagination({ current: 1, pageSize: 10 });
    }
  }, [initialParams, isStaticData]);

  // 分页变化处理
  const handlePaginationChange = useCallback((current: number, pageSize?: number) => {
    setPagination(prev => ({
      current,
      pageSize: pageSize || prev.pageSize,
    }));
  }, []);

  // 计算最终显示的数据
  const displayData = useMemo(() => {
    return filter ? filteredData : data;
  }, [filter, filteredData, data]);

  // 计算分页后的数据
  const paginatedData = useMemo(() => {
    if (paginationConfig === false || isStaticData) {
      return displayData;
    }
    
    const startIndex = (pagination.current - 1) * pagination.pageSize;
    const endIndex = startIndex + pagination.pageSize;
    return displayData.slice(startIndex, endIndex);
  }, [displayData, pagination.current, pagination.pageSize, paginationConfig, isStaticData]);

  // 计算显示的总数
  const displayTotal = useMemo(() => {
    if (isStaticData) {
      return filter ? filteredData.length : data.length;
    }
    return filter ? filteredData.length : total;
  }, [isStaticData, filter, filteredData.length, data.length, total]);

  // 表格配置
  const tableProps: TableProps<T> = useMemo(() => ({
    columns,
    dataSource: paginatedData,
    loading,
    rowKey,
    pagination: false,
    scroll: { x: 800 },
  }), [columns, paginatedData, loading, rowKey]);

  // 分页配置
  const paginationProps: PaginationProps = useMemo(() => {
    if (paginationConfig === false) {
      return {} as PaginationProps;
    }

    const baseProps: PaginationProps = {
      current: pagination.current,
      pageSize: pagination.pageSize,
      total: displayTotal,
      showSizeChanger: true,
      showQuickJumper: true,
      showTotal: (total, range) => 
        `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
      onChange: handlePaginationChange,
      onShowSizeChange: handlePaginationChange,
    };

    // 合并自定义分页配置
    return typeof paginationConfig === 'object' 
      ? { ...baseProps, ...paginationConfig } 
      : baseProps;
  }, [pagination.current, pagination.pageSize, displayTotal, handlePaginationChange, paginationConfig]);

  // 筛选输入框配置
  const filterProps: InputProps = useMemo(() => ({
    value: filterValue,
    onChange: (e) => handleFilterChange(e.target.value),
    placeholder: filter?.placeholder || `搜索${filter?.dataIndex}`,
    allowClear: true,
    style: { width: 250 },
  }), [filterValue, handleFilterChange, filter]);

  return {
    // 核心属性
    tableProps,
    data: paginatedData,
    loading,
    total: displayTotal,
    
    // 分页相关
    paginationProps,
    current: pagination.current,
    pageSize: pagination.pageSize,
    
    // 筛选相关
    filterProps,
    filterValue,
    
    // 操作方法
    refresh,
    search,
    reset,
    setData,
    setLoading,
  };
};
